from django.shortcuts import render
# 导入日期模块
from datetime import datetime, timedelta
from utils import sqlhelper
import json


def echart_basic(request):
    #  提供默认的值
    city = "上海市"
    today_date = datetime.now()

    # 判断是不是post请求
    if request.method == "POST":
        if len(request.POST.get('q_city')) != 0:
            city = request.POST.get('q_city')

        # 处理接收的日期
        date_str = (request.POST.get('q_date')).split("-")
        today_date = datetime(int(date_str[0]), int(date_str[1]),int(date_str[2]),0,0,0)

    #==== 准备传递到前台数据=====
    data = {}
    # 添加城市
    data['city'] = city
    # 添加日期
    data['today'] = today_date.strftime("%Y-%m-%d")
    # 添加天气
    data['temp'] = get_hight_low_temp(city, today_date)

    # ========返回到前端页面==============
    return render(request, 'echartsweb/echarts_demo1.html', {'weather': json.dumps(data)})


def get_hight_low_temp(city, today):
    """获取某一个城市未来7天的天气"""
    # 获取今天的日期

    today_str = today.strftime("%Y-%m-%d")
    seven_day = (today + timedelta(days=7)).strftime("%Y-%m-%d")
    # 准备sql
    sql = "Select Date, Hight, Low from CityWeather where Date>='%s' and Date<='%s' and Area='%s';" % (
    today_str, seven_day, city)
    # 获取数据
    response = sqlhelper.get_db_data(sql)
    # 准备三组数据  -- temp = { 'date' :[], 'hight:[], 'low': []}
    temp = {'date': [], 'hight': [], 'low': []}
    # 遍历
    for value in response['data']:
        temp['date'].append(value[0].strftime("%m-%d"))
        temp['hight'].append(value[1])
        temp['low'].append(value[2])
    # 返回
    return temp
